/*
 * Copyright (c) 2020 SakuraTJ.
 * https://github.com/SakuraTJ
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import file from '@system.file';
export default function fstorage(){

}

fstorage.init=function(){
    judgeDir('fstorage');
}

//获取存储内容
fstorage.get=function(key){
    /*
    *key:String
    */
    if(typeof key != 'string'){
        console.log('[key]variable type error:'+ typeof key);
    }

    let keyuri = 'fstorage/' + key;
    let value=null;
    file.access({
        uri: 'internal://app/' + keyuri,
        success: function() {
            //console.log(keyuri + 'existed.');
            file.list({
                uri: 'internal://app/' + keyuri,
                success: function(data) {
                    value=data.fileList[0].uri;
                },
                fail: function(data, code) {
                    console.error('get value fail, code: ' + code + ', data: ' + data);
                },
            });
        },
        fail: function(data, code) {
            console.error('do not find '+keyuri+', code: ' + code + ', data: ' + data);
        },
    });
    return value;
}
//修改存储内容
fstorage.set=function(key,value){
    /*
    *key:String
    *value:String
    * value值中不支持包含特殊符号，如\/:*?"<>|
    */
    if(typeof key != 'string'){
        console.log('[key]variable type error:'+ typeof key);
    }
    if(typeof value != 'string'){
        console.log('[value]variable type error:'+ typeof value);
    }

    fstorage.init();
    let keyuri = 'fstorage/' + key;
    let valueuri = keyuri + '/' + value;

    //新建KEY
    judgeDir(keyuri);

    //若有旧Value值，则删除
    file.list({
        uri: 'internal://app/' + keyuri,
        //success:说明存在旧Value值
        success: function(data) {
            let valueurinew = 'internal://app/' + keyuri + '/'+data.fileList[0].uri+'/';
            file.rmdir({
                uri: valueurinew,
                success: function() {
                    console.log('rm old value success.');
                },
                fail: function(data, code) {
                    console.error('rm old value: '+ valueurinew +' fail, code: ' + code + ', data: ' + data);
                },
            });
        },
        //无Value值
        fail: function(data, code) {
            //新建Value
        },
    });

    //新建Value
    file.mkdir({
        uri: 'internal://app/' + valueuri,
        success: function() {
            console.log('mk '+ valueuri +' success.');
        },
        fail: function(data, code) {
            console.error('mk '+ valueuri +' fail, code: ' + code + ', data: ' + data);
        },
    });

}

//清空存储内容
fstorage.clear=function(){
    file.list({
        uri: 'internal://app/fstorage',
        success: function(data) {
            let datalen = Object.keys(data.fileList).length;
            //递归,删除所有KEY文件夹
            for(let i=0;i<datalen;i++)
            {
                deleteDir('internal://app/fstorage/',data.fileList[i].uri);
            }
        },
    });
    deleteDir('internal://app/','fstorage');
    deleteDir('internal://app/','fstorage');//预防出现不知道什么原因出现的 300 I/O错误。。
}

//删除存储内容
fstorage.delete=function(key){
    /*
    *key:String
    */
    if(typeof key != 'string'){
        console.log('[key]variable type error:'+ typeof key);
    }
    deleteDir('internal://app/fstorage/',key);
}


//判断文件夹是否存在，若不存在新建
function judgeDir(filename){
    /*
    *filename:String
    */
    file.access({
        uri: 'internal://app/' + filename,
        success: function() {
            console.log(filename + ' has existed.');
        },
        fail: function(data, code) {
            //console.error('do not find '+filename +', code: ' + code + ', data: ' + data);
            file.mkdir({
                uri: 'internal://app/' + filename,
                success: function() {
                    console.log('mk '+ filename +' success.');
                },
                fail: function(data, code) {
                    console.log('mk '+ filename +' fail, code: ' + code + ', data: ' + data);
                },
            });
        },
    });
}

//删除文件夹及其子文件夹
function deleteDir(rooturi,filename){
    /*
    *rooturi:绝对路径，如 'internal://app/'
    * filename:文件夹名称
    */
    file.access({
        uri: rooturi + filename,
        success: function() {
            file.rmdir({
                uri: rooturi + filename,
                //若无子文件夹可删除成功
                success: function() {
                    console.log('delete ['+ rooturi + filename +'] success.');
                },
                //含有子文件夹
                fail: function(data, code) {
                    file.list({
                        uri: rooturi + filename,
                        success: function(data) {
                            let datalen = Object.keys(data.fileList).length;
                            //有子文件夹，递归,删除子文件夹
                            for(let i=0;i<datalen;i++)
                            {
                                deleteDir(rooturi + filename + '/',data.fileList[i].uri);
                            }
                            //删除当前节点父文件夹
                            file.rmdir({
                                uri: rooturi + filename,
                                success: function() {
                                    console.log('delete ['+ rooturi + filename +'] success.');
                                },
                                fail: function(data, code) {
                                    console.error('delete ['+ rooturi + filename +'] fail, code: ' + code + ', data: ' + data);
                                },
                            });
                        },
                        fail: function(data, code) {
                            console.error('list ['+ rooturi + filename +'] fail, code: ' + code + ', data: ' + data);
                        },
                    });
                },
            });

        },
        fail: function(data, code) {
            console.log('[deleteDir] isnt exist, code: ' + code + ', data: ' + data);
        },
    });
}